<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * The web entrance. index.php is not only a php page, but also
 * interpret the path coming from the browser!
 * What a fancy thing!
 * 
 * 整个网站的入口, 带有路径解析与路由功能!
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.1
 */

// TODO: Something about performace detecting, startTime()?

// Entrance flag definition.
define('XMUSLH', true);
// The based installation directory.
define('INSTALLDIR', dirname(__FILE__));

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// TODO: The friendly shutodown function?

/*
 * Temproray includements manully.
 */
require_once INSTALLDIR . '/actions/slh_first.php';

// Requirements!
require_once INSTALLDIR . '/lib/slh_init.php';

/**
 * The method to get the path on the browser.
 * 
 * @param array		$req			$_REQUEST
 */
function slh_get_path($req)
{
	// Eliminate the fancy? in StatusNet.
	if (array_key_exists('PATH_INFO', $_SERVER)) {
		$path = $_SERVER['PATH_INFO'];
		$script = $_SERVER['SCRIPT_NAME'];
		
		if (substr($path, 0, mb_strlen($script)) == $script) {
			return substr($path, mb_strlen($script));
		} else {
			return $path;
		}
	} else {
		return null;
	}
}

/**
 * FIXME: To what?
 * logs and then displays error messages
 */
function handleError($error)
{
    if ($error instanceof DB_DataObject_Error
        || $error instanceof DB_Error
    ) {
        $msg = sprintf(
            _(
                'The database for %s isn\'t responding correctly, '.
                'so the site won\'t work properly. '.
                'The site admins probably know about the problem, '.
                'but you can contact them at %s to make sure. '.
                'Otherwise, wait a few minutes and try again.'
            ),
            'xmuslh',
            'xmuslh@qq.com'
        );
    } else {
        $msg = _(
            'An important error occured, probably related to email setup. '.
            'Check logfiles for more info..'
        );
    }

    echo $msg;
    exit(-1);
}

/** 
 * Main entrance.
 */
function slh_main()
{
	/*
	 * We are not going to use lighttpd! Eliminates the judgement,
	 * haha!
	 */
	
	// Get the current url!
	$_SERVER['REDIRECT_URL'] = preg_replace("/\?.+$/", "", $_SERVER['REQUEST_URI']);
	
// TODO: $user logins and $action performs here, later.
// TODO: What is a snapshot?

// FIXME: Check the config file.
	if ( !true) {
		die("No Config.");
	}
	
	// TODO: The database error handler.
	// For database errors
    PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
	
// TODO: Something about database and read/write previlege?
// TODO: Initialze the $user and language environment!

	/*
	 * Get the path and do routing.
	 * To get the '/groups', '/notice', etc.
	 * 
	 * URL:		http://localhost/StatusNet/statusnet-0.9.7fix1/index.php/groups
	 * $path:	/groups
	 */
	$path = slh_get_path($_REQUEST);
	
//TODO: Get implements a router!!!
	/*
	 * Emulates one for test...
	 * $r = Router::get();
	 * $args = $r->map($path);
	 */
	/*
	$args = array();
///////////////////////////////////////////////////////////Change the action. ///
	$args['action'] = 'getinfo';
	$args['args'] = 'some value';
/////////////////////////////////////////////////////////////////////////////////
	*/
	
	$router = Router::get();
	$args = $router->map($path);
	if ( !$args) {
// TODO: ClientErrorAction
        echo 'Page not found!<br />';
        return;
    }
    
    // Test the build()!
    // Get the relative path.
	$path = $router->build($args['action'], $args);
/*    
var_dump($args);
var_dump($path);
*/	

	$args = array_merge($args, $_REQUEST);
	//Generate an action.
	$action = $args['action'];
	
	// Illegal action.
	if ( !$action || !preg_match('/^[a-zA-Z0-9_-]*$/', $action)) {
// TODO: A common redirection!
        die("Illegal action!");
    }
    
// TODO: Check if closing or being private.

    // Generate an action class.
    $action_class = ucfirst($action) . 'Action';
    
    // Validates the class.
    if ( !class_exists($action_class)) {
    	die("No such class.");
    } else {
    	// Loading...
    	$action_obj = new $action_class();
    	
    	// Do the execution via such action mapping.
    	try {
    		if ($action_obj->prepare($args)) {
    			// Prepare() done!
    			$action_obj->handle($args);
    		}
    	} catch (Exception $e) {
// TODO: Exception handlers.
    		// Many related exception handlers.
    	}
    }
}

// Go!
slh_main();